import { ref } from 'vue'
import { defineStore } from 'pinia'
import apiClient from '../services/api'

// 定义API配置类型
export interface ApiConfig {
  baseUrl: string
  timeout: number
  retryCount: number
  corsEnabled: boolean
  openaiBase?: string // 用于指向远程Ollama服务的OPENAI_BASE
}

// 定义模型配置类型
export interface ModelConfig {
  name: string
  path: string
  type: 'gptq' | 'bnb' | 'fp16' | 'fp32' | 'ollama'
  quantBits: number
  useCache: boolean
  cacheSize: number
  deviceMap: string
}

// 定义RAG配置类型
export interface RagConfig {
  enabled: boolean
  embeddingModel: string
  topK: number
  scoreThreshold: number
  chunkSize: number
  chunkOverlap: number
  maxContextSize: number
}

// 定义工具配置类型
export interface ToolConfig {
  webSearch: {
    enabled: boolean
    provider: string
    apiKey: string
    maxResults: number
  }
  databaseQuery: {
    enabled: boolean
    connectionString: string
    allowedTables: string[]
  }
  fileOperation: {
    enabled: boolean
    allowedPaths: string[]
    readOnly: boolean
  }
}

// 定义学习配置类型
export interface LearningConfig {
  enabled: boolean
  trainingBatchSize: number
  learningRate: number
  numEpochs: number
  adapterName: string
  loraRank: number
  loraAlpha: number
  loraDropout: number
}

// 定义日志配置类型
export interface LogConfig {
  level: 'debug' | 'info' | 'warn' | 'error'
  fileEnabled: boolean
  fileSize: number
  fileRetention: number
  consoleEnabled: boolean
}

// 系统设置store
export const useSettingsStore = defineStore('settings', () => {
  // API配置
  const apiConfig = ref<ApiConfig>({
    baseUrl: '',
    timeout: 60000,
    retryCount: 3,
    corsEnabled: true,
    openaiBase: '' // 用于指向远程Ollama服务的OPENAI_BASE
  })
  
  const modelConfig = ref<ModelConfig>({
    name: 'qwen2.5:7b',
    path: 'qwen2.5:7b',
    type: 'ollama',
    quantBits: 4,
    useCache: true,
    cacheSize: 1024,
    deviceMap: 'auto'
  })
  
  const ragConfig = ref<RagConfig>({
    enabled: true,
    embeddingModel: 'all-MiniLM-L6-v2',
    topK: 5,
    scoreThreshold: 0.5,
    chunkSize: 512,
    chunkOverlap: 64,
    maxContextSize: 4096
  })
  
  const toolConfig = ref<ToolConfig>({
    webSearch: {
      enabled: true,
      provider: 'google',
      apiKey: '',
      maxResults: 3
    },
    databaseQuery: {
      enabled: false,
      connectionString: '',
      allowedTables: []
    },
    fileOperation: {
      enabled: true,
      allowedPaths: [],
      readOnly: true
    }
  })
  
  const learningConfig = ref<LearningConfig>({
    enabled: true,
    trainingBatchSize: 4,
    learningRate: 0.0001,
    numEpochs: 3,
    adapterName: 'lora-finetune',
    loraRank: 8,
    loraAlpha: 32,
    loraDropout: 0.1
  })
  
  const logConfig = ref<LogConfig>({
    level: 'info',
    fileEnabled: true,
    fileSize: 10,
    fileRetention: 7,
    consoleEnabled: true
  })
  
  const isLoading = ref<boolean>(false)
  const isSaving = ref<boolean>(false)
  const activeTab = ref<string>('api') // 'api', 'model', 'rag', 'tools', 'learning', 'logs'

  // 加载系统配置
  const loadSystemConfig = async () => {
    isLoading.value = true
    try {
      // 调用API获取系统配置
      const response = await apiClient.get('/v1/settings')
      if (response.data.apiConfig) apiConfig.value = response.data.apiConfig
      if (response.data.modelConfig) modelConfig.value = response.data.modelConfig
      if (response.data.ragConfig) ragConfig.value = response.data.ragConfig
      if (response.data.toolConfig) toolConfig.value = response.data.toolConfig
      if (response.data.learningConfig) learningConfig.value = response.data.learningConfig
      if (response.data.logConfig) logConfig.value = response.data.logConfig
    } catch (error) {
      console.error('加载系统配置失败:', error)
    } finally {
      isLoading.value = false
    }
  }



  // 保存系统配置
  const saveSystemConfig = async () => {
    isSaving.value = true
    try {
      // 调用API保存系统配置
      await apiClient.put('/v1/settings', {
        apiConfig: apiConfig.value,
        modelConfig: modelConfig.value,
        ragConfig: ragConfig.value,
        toolConfig: toolConfig.value,
        learningConfig: learningConfig.value,
        logConfig: logConfig.value
      })
      return true
    } catch (error) {
      console.error('保存系统配置失败:', error)
      return false
    } finally {
      isSaving.value = false
    }
  }



  // 恢复默认配置
  const restoreDefaultConfig = async () => {
    try {
      // 重置为默认配置
      apiConfig.value = {
        baseUrl: '/api',
        timeout: 60000,
        retryCount: 3,
        corsEnabled: true
      }
      
      modelConfig.value = {
        name: 'Qwen2.5-3B-Instruct-GPTQ-4bit',
        path: 'models/Qwen2.5-3B-Instruct-GPTQ-4bit',
        type: 'gptq',
        quantBits: 4,
        useCache: true,
        cacheSize: 1024,
        deviceMap: 'auto'
      }
      
      ragConfig.value = {
        enabled: true,
        embeddingModel: 'all-MiniLM-L6-v2',
        topK: 5,
        scoreThreshold: 0.5,
        chunkSize: 512,
        chunkOverlap: 64,
        maxContextSize: 4096
      }
      
      toolConfig.value = {
        webSearch: {
          enabled: true,
          provider: 'google',
          apiKey: '',
          maxResults: 3
        },
        databaseQuery: {
          enabled: false,
          connectionString: '',
          allowedTables: []
        },
        fileOperation: {
          enabled: true,
          allowedPaths: [],
          readOnly: true
        }
      }
      
      learningConfig.value = {
        enabled: true,
        trainingBatchSize: 4,
        learningRate: 0.0001,
        numEpochs: 3,
        adapterName: 'lora-finetune',
        loraRank: 8,
        loraAlpha: 32,
        loraDropout: 0.1
      }
      
      logConfig.value = {
        level: 'info',
        fileEnabled: true,
        fileSize: 10,
        fileRetention: 7,
        consoleEnabled: true
      }
      
      // 保存默认配置
      await saveSystemConfig()
      return true
    } catch (error) {
      console.error('恢复默认配置失败:', error)
      return false
    }
  }

  // 导出配置
  const exportConfig = async () => {
    try {
      // 构建导出数据
      const exportData = {
        apiConfig: apiConfig.value,
        modelConfig: modelConfig.value,
        ragConfig: ragConfig.value,
        toolConfig: toolConfig.value,
        learningConfig: learningConfig.value,
        logConfig: logConfig.value,
        exportTime: new Date().toISOString()
      }
      
      // 转换为JSON字符串
      const jsonString = JSON.stringify(exportData, null, 2)
      
      // 创建Blob对象
      const blob = new Blob([jsonString], { type: 'application/json' })
      
      // 创建下载链接
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `ai-assistant-config-${Date.now()}.json`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      
      return true
    } catch (error) {
      console.error('导出配置失败:', error)
      return false
    }
  }

  // 导入配置
  const importConfig = async (file: File) => {
    try {
      return new Promise<boolean>((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (event) => {
          try {
            if (event.target?.result) {
              const importedConfig = JSON.parse(event.target.result as string)
              
              // 更新配置
              if (importedConfig.apiConfig) {
                apiConfig.value = importedConfig.apiConfig
              }
              if (importedConfig.modelConfig) {
                modelConfig.value = importedConfig.modelConfig
              }
              if (importedConfig.ragConfig) {
                ragConfig.value = importedConfig.ragConfig
              }
              if (importedConfig.toolConfig) {
                toolConfig.value = importedConfig.toolConfig
              }
              if (importedConfig.learningConfig) {
                learningConfig.value = importedConfig.learningConfig
              }
              if (importedConfig.logConfig) {
                logConfig.value = importedConfig.logConfig
              }
              
              // 保存更新后的配置
              saveSystemConfig().then(() => {
                resolve(true)
              }).catch(() => {
                resolve(false)
              })
            } else {
              reject(new Error('文件读取失败'))
            }
          } catch (e) {
            reject(new Error('配置文件格式错误'))
          }
        }
        reader.onerror = () => {
          reject(new Error('文件读取失败'))
        }
        reader.readAsText(file)
      })
    } catch (error) {
      console.error('导入配置失败:', error)
      return false
    }
  }

  // 获取系统状态
  const getSystemStatus = async () => {
    try {
      // 调用API获取系统状态
      const response = await apiClient.get('/v1/settings/status')
      return response.data
    } catch (error) {
      console.error('获取系统状态失败:', error)
      return null
    }
  }



  // 切换选项卡
  const switchTab = (tab: string) => {
    activeTab.value = tab
  }

  return {
    // 状态
    apiConfig,
    modelConfig,
    ragConfig,
    toolConfig,
    learningConfig,
    logConfig,
    isLoading,
    isSaving,
    activeTab,
    // 方法
    loadSystemConfig,
    saveSystemConfig,
    restoreDefaultConfig,
    exportConfig,
    importConfig,
    getSystemStatus,
    switchTab
  }
})